<template>
    <div class="study_report_container">
        <div class="study_report">
            <div class="filters">
                <label>选择学生：</label>
                <select v-model="selectedStudentId">
                    <option v-for="student in students" :key="student.student_id" :value="student.student_id">
                        {{ student.name }}
                    </option>
                </select>
                <button @click="loadReport">加载报告</button>
            </div>

            <div class="charts-container">
                <div class="chart-wrapper">
                    <div class="chart" ref="dailyChart"></div>
                </div>
                <div class="chart-wrapper">
                    <div class="chart" ref="weeklyChart"></div>
                </div>
                <div class="chart-wrapper">
                    <div class="chart" ref="curveChart"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ApiService } from '@/api/apiService';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

// 学生数据
const students = ref([]);
// 初始化数据
async function fetchItems() {
    try {
        const userId = userStore.getUser?.user_id;
        if (!userId) throw new Error('User ID not found');

        const response = await ApiService.getStudentsList(userId);
        console.log('获取学生列表成功:', response.data.code);
        if (response.data.code === 200) {
            students.value = response.data.data;
            loadPlans();
        } else {
            console.error('获取学生列表失败:', response.data);
        }
    } catch (error) {
        console.error('error:', error);
    }
}


// 图表DOM引用
const dailyChart = ref(null);
const weeklyChart = ref(null);
const curveChart = ref(null);

// 图表实例
let dailyChartInstance = null;
let weeklyChartInstance = null;
let curveChartInstance = null;

// 确保DOM已挂载后再初始化图表
const initCharts = () => {
    if (!dailyChartInstance && dailyChart.value) {
        dailyChartInstance = echarts.init(dailyChart.value);
    }
    if (!weeklyChartInstance && weeklyChart.value) {
        weeklyChartInstance = echarts.init(weeklyChart.value);
    }
    if (!curveChartInstance && curveChart.value) {
        curveChartInstance = echarts.init(curveChart.value);
    }
};

const selectedStudentId = ref(1);

// 定义数据
const daily_report = ref({});
const weekly_report = ref({});
const curve_report = ref({});

const generateMockData = () => ({
    daily: Array.from({ length: 30 }, (_, i) => ({
        date: new Date(Date.now() - (30 - i) * 86400000).toISOString().split('T')[0],
        rate: Math.floor(60 + Math.random() * 40),
        total: Math.floor(10 + Math.random() * 15)
    })),
    weekly: Array.from({ length: 12 }, (_, i) => ({
        week: `第${12 - i}周`,
        rate: Math.floor(50 + Math.random() * 45)
    })),
    curve: [1, 2, 4, 7, 15].map(days => ({
        days,
        rate: Math.min(100, 100 * Math.pow(0.6, days / 5) + Math.random() * 5)
    }))
});

const loadReport = async () => {
    // 确保DOM已更新
    await nextTick();

    // 初始化图表实例（如果未初始化）
    initCharts();

    const daily_report_response = await ApiService.get_daily_report(selectedStudentId.value);
    console.log('获取每日报告成功:', daily_report_response.data);
    if (daily_report_response.data.code === 200) {
        daily_report.value = daily_report_response.data.data;
    } else {
        console.error('获取每日报告失败:', daily_report_response.data);
    }
    const weekly_report_response = await ApiService.get_weekly_report(selectedStudentId.value);
    console.log('获取每周报告成功:', weekly_report_response.data);
    if (weekly_report_response.data.code === 200) {
        weekly_report.value = weekly_report_response.data.data;
    } else {
        console.error('获取每周报告失败:', weekly_report_response.data);
    }
    const curve_report_response = await ApiService.get_forget_curve(selectedStudentId.value);
    console.log('获取遗忘曲线成功:', curve_report_response.data);
    if (curve_report_response.data.code === 200) {
        curve_report.value = curve_report_response.data.data;
    } else {
        console.error('获取遗忘曲线失败:', curve_report_response.data);
    }

    const mockData = generateMockData();

    // 安全调用setOption
    try {
        dailyChartInstance?.setOption({
            title: { text: '每日完成率', left: 'center' },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: 'category',
                data: daily_report.value.map(d => d.date)
            },
            yAxis: [
                { name: '完成率(%)', type: 'value', min: 0, max: 100 },
                { name: '任务量', type: 'value', min: 0 }
            ],
            series: [
                {
                    name: '完成率',
                    type: 'line',
                    smooth: true,
                    data: daily_report.value.map(d => d.rate),
                    yAxisIndex: 0,
                    itemStyle: { color: '#5470C6' }
                },
                {
                    name: '任务量',
                    type: 'bar',
                    data: daily_report.value.map(d => d.total),
                    yAxisIndex: 1,
                    itemStyle: { color: '#91CC75' }
                }
            ]
        });

        weeklyChartInstance?.setOption({
            title: {
                text: '每周学习完成率',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    const data = params[0].data;
                    return `
                <strong>${params[0].axisValue}</strong><br/>
                日期范围: ${data.start_date} ~ ${data.end_date}<br/>
                总任务数: <span style="color: #5470C6">${data.total}</span><br/>
                已完成数: <span style="color: #91CC75">${data.completed}</span><br/>
                完成率: <span style="color: #73C0DE">${data.value}%</span>
            `;
                }
            },
            legend: {
                data: ['完成率', '已完成任务数'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                top: '20%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: weekly_report.value.map(w => w.week),
                axisLabel: {
                    rotate: 45,
                    interval: Math.ceil(weekly_report.value.length / 10) // 自动调整标签密度
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '完成率(%)',
                    min: 0,
                    max: 100,
                    axisLine: { show: true },
                    axisLabel: { formatter: '{value}%' }
                },
                {
                    type: 'value',
                    name: '任务数',
                    min: 0,
                    axisLine: { show: true },
                    splitLine: { show: false }
                }
            ],
            series: [
                {
                    name: '完成率',
                    type: 'line',
                    smooth: true,
                    data: weekly_report.value.map(w => ({
                        value: w.rate,
                        start_date: w.start_date,
                        end_date: w.end_date,
                        total: w.total,
                        completed: w.completed
                    })),
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: 'rgba(115, 192, 222, 0.8)'
                            }, {
                                offset: 1,
                                color: 'rgba(115, 192, 222, 0.1)'
                            }]
                        }
                    },
                    itemStyle: { color: '#73C0DE' },
                    lineStyle: { width: 3 }
                },
                {
                    name: '已完成任务数',
                    type: 'bar',
                    yAxisIndex: 1,
                    data: weekly_report.value.map(w => w.completed),
                    itemStyle: {
                        color: '#91CC75',
                        borderRadius: [4, 4, 0, 0]
                    },
                    barWidth: '60%'
                }
            ]
        });

        curveChartInstance?.setOption({
            title: {
                text: '遗忘曲线分析',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    const data = params[0].data;
                    return `
                <strong>${data.time_label}</strong><br/>
                理论记忆率: <span style="color:#5470C6">${data.theoretical_rate}%</span><br/>
                实际记忆率: <span style="color:#91CC75">${data.actual_rate}%</span><br/>
                复习次数: ${data.review_count}
            `;
                }
            },
            legend: {
                data: ['理论曲线', '实际记忆'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                top: '20%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: curve_report.value.map(item => item.time_label),
                axisLabel: {
                    interval: 0,
                    // 改为90度垂直排列
                    // verticalAlign: 'middle',
                    align: 'center',
                    margin: 20,   // 增加边距防止重叠
                    lineHeight: 20,
                    formatter: function (value) {
                        // 新改进的格式化函数：文字竖排，数字保持横排
                        let result = [];
                        let tempStr = '';

                        for (let i = 0; i < value.length; i++) {
                            const char = value[i];
                            if (/\d/.test(char)) {
                                // 如果是数字，暂存起来
                                tempStr += char;
                            } else {
                                // 如果不是数字，先把之前暂存的数字处理掉
                                if (tempStr) {
                                    result.push(tempStr);
                                    tempStr = '';
                                }
                                // 当前非数字字符单独处理
                                result.push(char);
                            }
                        }

                        // 处理最后剩余的数字
                        if (tempStr) {
                            result.push(tempStr);
                        }

                        return result.join('\n');
                    }
                }
                // ,
                // axisTick: {
                //     alignWithLabel: true
                // },
                // axisLine: {
                //     lineStyle: {
                //         color: '#333'
                //     }
                // }
            },
            yAxis: {
                type: 'value',
                name: '记忆保留率(%)',
                min: 0,
                max: 100,
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            series: [
                {
                    name: '理论曲线',
                    type: 'line',
                    data: curve_report.value.map(item => ({
                        value: [
                            item.time_label,
                            item.theoretical_rate,
                            item.actual_rate,
                            item.review_count
                        ],
                        ...item  // 保留原始数据
                    })),
                    lineStyle: { width: 3, color: '#5470C6' }
                },
                {
                    name: '实际记忆',
                    type: 'scatter',
                    data: curve_report.value.map(item => ({
                        value: [
                            item.time_label,
                            item.actual_rate,
                            item.theoretical_rate,
                            item.review_count
                        ],
                        ...item  // 保留原始数据
                    })),
                    symbolSize: function (data) {
                        // 安全访问review_count
                        return 8 + Math.min(12, data.review_count || 0);
                    },
                    itemStyle: { color: '#91CC75' }
                }
            ]
        });
    } catch (error) {
        console.error('图表渲染错误:', error);
    }
};

onMounted(async () => {
    await fetchItems()

    // 初始加载数据
    loadReport();


    // 窗口变化自适应
    window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    [dailyChartInstance, weeklyChartInstance, curveChartInstance].forEach(
        chart => chart?.dispose()
    );
});

const handleResize = () => {
    [dailyChartInstance, weeklyChartInstance, curveChartInstance].forEach(
        chart => chart?.resize()
    );
};
</script>


<style scoped>
    @import url("@/assets/css/study_report.css");

    .charts-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        padding: 20px;
    }

    .chart-wrapper {
        height: 400px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        padding: 15px;
    }

    .chart {
        width: 100%;
        height: 100%;
    }

    .filters {

        background: #f5f7fa;
        border-radius: 8px;
        margin-bottom: 20px;
    }

</style>